package cn.net.msg.utils;

//import com.isch.zh.hw.util.IsChineseUtil;  

public class Conversion {

	/**
	 * 中文转-->unicode
	 * 
	 * @param str
	 * @return 反回unicode编码
	 */
	public static String chinaToUnicode(String str) {

		StringBuffer result = new StringBuffer();
		for (int i = 0; i < str.length(); i++) {
			int chr1 = (char) str.charAt(i);
			result.append("\\u" + Integer.toHexString(chr1));

		}
		return result.toString();
	}

	/**
	 * unicode转-->中文
	 * 
	 * @param str
	 * @return 中文
	 */
	/*
	 * public static String unicodeToChinese(String str) { StringBuffer sb = new
	 * StringBuffer(); for (char c : str.toCharArray()) { sb.append(c); } return
	 * sb.toString(); }
	 */
	public String abc() {

		return "abc";
	}

	/**
	 * 把unicode转化为中文
	 * 
	 * @param str
	 * @return
	 */
	public static String unicodeToChinese(String str) {

		if (str.indexOf("\\u") == -1 || str == null || "".equals(str.trim())) {/* 若不是unicode，则直接返回 */
			return str.replaceAll("\\\\ ", " ");// 删掉英文中的\,such as "default\
												// value1"
			/* 主要是针对 zk 中的国际化问题 */
		}
		StringBuffer sb = new StringBuffer();
		if (!str.startsWith("\\u")) {/* 若开头不是unicode，如“abc\u4e2d\u56fd” */
			int index = str.indexOf("\\u");
			sb.append(str.substring(0, index));
			str = str.substring(index);
		}
		if (str.endsWith(":")) /* 如“\u4e2d\u56fd：” */{
			str = str.substring(0, str.length() - 1);
		}
		String[] chs = str.trim().split("\\\\u");

		for (int i = 0; i < chs.length; i++) {
			String ch = chs[i].trim();
			if (ch != null && !"".equals(ch)) {

				sb.append((char) Integer.parseInt(ch.substring(0, 4), 16));
				if (ch.length() > 4) {
					sb.append(ch.substring(4));
				}
			}
		}
		return sb.toString();
	}

	public static void main(String args[]) {

		// // unicode转中文
		// String str = "\u9ec42";
		// Conversion con = new Conversion();

		// System.out.println(con.unicodeToChinese(str));
		// System.out.println(Character.charCount(0x9ec4));
		// for(char c : str.toCharArray())
		// System.out.print(c);
		// System.out.println((char)Integer.parseInt("9ec4",16));
		Conversion conversion = new Conversion();
		System.out.println(conversion.chinaToUnicode("中文"));
		System.out.println(conversion.unicodeToChinese("\u4E09\u661F\uFF08\u0053\u0041\u004D\u0053\u0055\u004E\u0047\uFF09\u0020\u004E\u0058\u0031\u0030\u0030\u0030\u0020\u5355\u7535\u5957\u673A\uFF08\u0032\u0030\u006D\u006D\u002D\u0035\u0030\u006D\u006D\uFF09\uFF08\u767D\u8272\uFF09"));

	}

	public static String resolveUnicode(String oldValue, boolean isToUnicode) {

		if (isToUnicode) {
			return chinaToUnicode(oldValue);
		} else {
			return unicodeToChinese(new String(oldValue));
		}
	}

}